package com.michael.study.ipc;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.michael.study.ipc.databinding.ActivityMainBinding;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityMainBinding mBinding;

    private ServiceConnection mConnection =
            new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {
                    IBookManager manager = IBookManager.Stub.asInterface(service);
                    try {
                        Log.d("lgq", "onServiceConnected: " + Thread.currentThread().getName());

                        List<Book> books = manager.getBookList();
                        for (Book book : books) {
                            Log.d("lgq", "onServiceConnected: " + book.toString());
                        }

                        Book book = new Book(3, "JavaScript");
                        manager.addBook(book);

                        books = manager.getBookList();
                        for (Book b : books) {
                            Log.d("lgq", "onServiceConnected: " + b.toString());
                        }

                    } catch (RemoteException e) {

                    }
                }

                @Override
                public void onServiceDisconnected(ComponentName name) {}
            };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        mBinding.btnBind.setOnClickListener(this);
        mBinding.btnChange.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_bind) {
            Intent intent = new Intent(this,BookManagerService.class);
            bindService(intent,mConnection, Service.BIND_AUTO_CREATE);
        }
        if (v.getId() == R.id.btn_change) {
            mBinding.btnChange.setText("Just do it");
        }
    }
}
